<?php
/**
 * User: aka
 * Time: 18:50
 */

namespace app\input\controller;

use app\validator\users\ForgetPassword;
use app\validator\users\SignUp;
use think\facade\Session;
use think\Request;

class Users
{
    private function findSameAccount(string $account)
    {
        $data = \app\secret\model\Users::account($account)->find();
        return $data == null ? true : false;
    }

    private function deleteUserSession()
    {
        Session::delete('user_info');
    }

    public function signUp(Request $request)
    {
        $validate = new SignUp();
        if (!$validate->check($request->param())) {
            return json($validate->getError());
        }else {
            $checkResult = check_email_code($request->param('email_code'));
            if ($checkResult == false)
            {
                return json(602);
            }else{
                $addData = array();
                $addData['account'] = $request->param('account');
                $addData['name'] = $request->param('name');
                $addData['password'] = encode_password($request->param('password'));
                $findResult = $this->findSameAccount($request->param('account'));
                if ($findResult == false)
                {
                    return json(601);
                }else{
                    \app\secret\model\Users::create($addData);
                    return json(200);
                }
            }
        }
    }

    public function forgetPassword(Request $request)
    {
        $validate = new ForgetPassword();
        if (!$validate->check($request->param())) {
            return json($validate->getError());
        }else {
            $checkResult = check_email_code($request->param('email_code'));
            if ($checkResult == false)
            {
                return json(602);
            }else {
                $updateData = array();
                $updateData['password'] = encode_password($request->param('password'));
                $userData = \app\secret\model\Users::account($request->param('account'))->find();
                \app\secret\model\Users::where('id', $userData['id'])->update($updateData);
                $this->deleteUserSession();
                return json(200);
            }
        }
    }
    
    public function signOut()
    {
        $this->deleteUserSession();
    }
}